using UnityEngine;

namespace ZTools.ZSingletons
{
    /// 单例模式
    /// 单场景可用, 如果需要不同场景保持, 需使用ZPersistentSingleton
    public class ZSingleton<T> : MonoBehaviour where T : Component
    {
        protected static T _instance;
        private static bool HasInstance => _instance != null;

        public static T TryGetInstance() => HasInstance ? _instance : null;
        public static T Current => _instance;


        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = FindFirstObjectByType<T>();
                    if (_instance == null)
                    {
                        var obj = new GameObject
                        {
                            name = typeof(T).Name + "_AutoCreated"
                        };
                        _instance = obj.AddComponent<T>();
                    }
                }

                return _instance;
            }
        }

        protected virtual void Awake()
        {
            if (!Application.isPlaying)
            {
                return;
            }

            _instance = this as T;
        }
    }
}